<?php

namespace co2\dev\v0_0_0;

const
  channel='dev',
  version='0.0.0',
  Version='v0_0_0';

class runtime

{
	protected static
		$properties							=	array(),
		$error_handlers					=array(),
		$legacy_error_handler
		;
		
	protected
		$ini
		;
		
	public function
	__construct
	(
		$ini=null
	)
	
	{
		$this->ini=$ini;
		
		$this->readIni();
	}
	
	protected function
	readIni
	()
	{
		if(is_object($this->ini))
		
		{
			if(isset($this->ini->properties) && (is_array($this->ini->properties) || is_object($this->ini->properties)))
			foreach($this->ini->properties as $k=>$v)
			self::set_prop($k,$v);
			
			if(isset($this->ini->error_handlers) && is_array($this->ini->error_handlers))
			foreach($this->ini->error_handlers as $error_handler)
			if(is_callable($error_handler))
			self::register_error_handler($error_handler);
		}
	}
		
	protected static function set_prop($key,$value)
	
	{
		if(isset(self::$properties[$key]))
		self::$properties[$key]=$value;
		
		switch($key)
		
		{
			case'catch php errors':
			
				if($value===true)
				
				{
					$p=set_error_handler(array(__CLASS__,'handle_errors'));
					
					if(is_null(self::$legacy_error_handler))
					self::$legacy_error_handler=$p;
				}
				
				elseif($value===false && !is_null(self::$legacy_error_handler))
				set_error_handler(self::$legacy_error_handler);
			
			break;
		}
	}
		
	public static function register_error_handler($handler)
	
	{
		self::$error_handlers[]=$handler;
	}
	
	public static function handle_errors($level,$message,$file,$line,array $context=null)
	
	{
		foreach(self::$error_handlers as $handler)
		$handler($level,$message,$file,$line,$context);
	}
}

function autoload($class,$ping=false)

{
  $namespace='co2\\\\'.channel.'\\\\'.Version.'\\\\';
  
	if(preg_match('/^'.$namespace.'/',$class))
	
	{
		$file=preg_replace('/^'.$namespace.'/','',$class);

		$file=preg_replace('/\\\/','/',$file);

		$file=__DIR__.'/'.$file.'.php';

		if(!file_exists($file))
		throw new Exception('Could not autoload class '.$class);

		require_once $file;

		if(!class_exists($class))
		throw new Exception('class not found: '.$class);
	}
}

spl_autoload_register('co2\dev\v0_0_0\autoload');
